<?php

namespace App\Common\Lib;

use App\Common as com;
use \Hyperf\Validation\ValidatorFactory;

class Hyperf extends com\Lib\LibBase {

	public static bool $abc = false;

	// ===============================
	//
	//
	// 下面为静态方法
	//
	//
	// ===============================

	/**
	 * @return ValidatorFactory
	 */
	public static function newValidation(  ):ValidatorFactory {
		// return make( ValidatorFactory::class );
		$validatorFactory = \Hyperf\Support\make( ValidatorFactory::class );
		// 已定义验证规则
		$validatorFactory->extend('phone', function ($attribute, $value, $parameters, $validator) {
			if( preg_match( "/^1[34578]{1}\d{9}$/", $value ) ) {
				return true;
			}else{
				// 请填写正确电话
				return false;
			}
		});
		// 当创建一个自定义验证规则时，你可能有时候需要为错误信息定义自定义占位符这里扩展了 :foo 占位符
		$validatorFactory->replacer('phone', function ($message, $attribute, $rule, $parameters) {
			return str_replace(':phone', $attribute, $message);
		});
		//
		return $validatorFactory;
	}

	/**
	 * 获取配置，如果不存在则抛出异常
	 * @param string $key 配置key
	 * @param bool $failKeyInfo 异常信息是否包含配置key
	 * @return mixed
	 * @throws
	 */
	public static function configOrFail( string $key, bool $failKeyInfo = false ):mixed {
		$config = \Hyperf\Config\config( $key );
		if( $config === null ){
			$errMsg = '配置不存在';
			if( $failKeyInfo ){
				$errMsg .= "：{$failKeyInfo}";
			}
			throw com\Lib\Err\Exception::makeOfNew( $errMsg, com\Lib\Err\Code::$sysDataNotExist );
		}
		return $config;
	}
	
}
